package cn.suimg.web.util;

import cn.suimg.shortlink.util.HttpClientUtil;
import cn.suimg.shortlink.util.JSONUtil;
import cn.suimg.shortlink.vo.Role;
import cn.suimg.shortlink.vo.User;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import java.security.Principal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * SSO主角工具类
 */
@SuppressWarnings("unchecked")
public class PrincipalUtil {

    /**
     * 获取权限列表
     * @param principal
     * @return
     */
    public static List<Role> getRoles(Principal principal){
        if (principal != null) {
            OAuth2Authentication auth = (OAuth2Authentication) principal;
            Map<String, Object> details = (Map<String, Object>) auth.getUserAuthentication().getDetails();
            List<Object> roles = (List<Object>) details.get("roles");
            return roles.stream().map(obj -> {
                Map<String, String> roleItem = (Map<String, String>) obj;
                return new Role() {{
                    setId(roleItem.get("id"));
                    setName(roleItem.get("name"));
                    setDisplay(roleItem.get("display"));
                }};
            }).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 获取当前token
     * @param principal
     * @return
     */
    public static String getCurrentToken(Principal principal){
        if (principal != null) {
            OAuth2Authentication auth = (OAuth2Authentication) principal;
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails();
            return details.getTokenValue();
        }
        return null;
    }

    /**
     * 获取认证信息
     * @param principal
     * @return
     */
    public static User getDetails(Principal principal) {
        if (principal != null) {
            OAuth2Authentication auth = (OAuth2Authentication) principal;
             Map<String,Object> info = (Map<String, Object>) auth.getUserAuthentication().getDetails();
             return new User(){{
                 setId((String) info.get("id"));
                 setUsername((String) info.get("username"));
                 setEmail((String) info.get("email"));
                 setNickname((String) info.get("nickname"));
                 setAvatarUrl((String) info.get("avatarUrl"));
             }};
        }
        return null;
    }

    public static User getDetails(String token){
        if(token == null)
            return null;
        String userInfo = new HttpClientUtil()
                .post("https://sso.suimg.cn/user/me.do")
                .addHeader("authorization", String.format("Bearer %s", token))
                .exec()
                .getResponseData();
        return JSONUtil.toObject(userInfo,User.class);
    }

}
